package cn.com.miaoto.controller;

import cn.com.miaoto.base.common.ReturnMsg;
import cn.com.miaoto.model.LoginUser;
import cn.com.miaoto.model.Role;
import cn.com.miaoto.model.RoleUser;
import cn.com.miaoto.service.LoginUserService;
import cn.com.miaoto.service.RoleService;
import cn.com.miaoto.service.RoleUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录用户
 * Created by guo.chen on 2018/9/15.
 */
@RestController
@RequestMapping("loginUser")
public class LoginUserController {

    @Resource
    private LoginUserService loginUserService;
    @Resource
    private RoleService roleService;
    @Resource
    private RoleUserService roleUserService;

    @GetMapping("selectAll")
    public Map<String, Object> selectLoginUserAll(){
        try{
            LinkedHashMap<String, Object> resultmap = new LinkedHashMap<String, Object>();
            PageHelper.startPage(0, 20);
            List<LoginUser> loginUsers = this.loginUserService.selectAll();
            PageInfo<LoginUser> pageRusult =new PageInfo<LoginUser>(loginUsers);
            for(LoginUser loginUser : loginUsers){
                List<Role> roleList = roleService.selectRolesByUserId(String.valueOf(loginUser.getId()));
                StringBuffer sb = new StringBuffer();
                for (Role role : roleList) {
                    sb.append("," + role.getRoleName());
                }
                loginUser.setRoles(sb.toString().replaceFirst(",", ""));
            }

            resultmap.put("currpage", String.valueOf(pageRusult.getPageNum()));
            resultmap.put("totalpages", String.valueOf(pageRusult.getPages()));
            resultmap.put("totalrecords", String.valueOf(pageRusult.getTotal()));
            resultmap.put("datamap", loginUsers);
            return resultmap;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @GetMapping("selectByPrimaryKey")
    public ReturnMsg selectByPrimaryKey(String userId){
        try{
            LoginUser loginUser = this.loginUserService.selectByKey(userId);
            return new ReturnMsg(true,loginUser);
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnMsg(false);
        }
    }

    @PostMapping("edit")
    public ReturnMsg insert(HttpSession session, LoginUser loginUser){
        // 加密密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        LoginUser currentUser =(LoginUser) session.getAttribute("currentUser");
        try {
            if(StringUtils.isEmpty(loginUser.getId())){
                final String rawPassword = loginUser.getPassword();
                loginUser.setPassword(encoder.encode(rawPassword));
                loginUser.setCreator(currentUser.getUserId());
                loginUser.setCreateTime(LocalDateTime.now());
                return new ReturnMsg(this.loginUserService.saveNotNull(loginUser)>0);
            }else{
                // 加密密码
                if(!StringUtils.isEmpty(loginUser.getPassword()))
                    loginUser.setPassword(encoder.encode(loginUser.getPassword()));
                return new ReturnMsg(this.loginUserService.updateNotNull(loginUser)>0);
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnMsg(false);
        }
    }

    @PostMapping("updatePwd")
    public ReturnMsg update(HttpSession session, LoginUser loginUser){
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        LoginUser currentUser =(LoginUser) session.getAttribute("currentUser");
        try {
            if(loginUser.getOldPassword()!=null && encoder.matches(loginUser.getOldPassword(),currentUser.getPassword())){
                loginUser.setPassword(encoder.encode(loginUser.getPassword()));
                if(this.loginUserService.updateNotNull(loginUser)>0){
                    currentUser.setPassword(loginUser.getPassword());
                    session.setAttribute("currentUser",currentUser);
                }
                return new ReturnMsg(true,"修改密码成功");
            }else {
                return new ReturnMsg(false,"旧密码错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ReturnMsg(false,"系统异常");
        }
    }

    @ResponseBody
    @GetMapping(value = "/selectRolesByUserId")
    public Map<String, Object> selectUserById(String userId) {
        LinkedHashMap<String, Object> resultmap = new LinkedHashMap<String, Object>();
        try {
            List<Role> roleList = roleService.selectRolesByUserId(userId);
            resultmap.put("roleList",roleList);//用户拥有的所有角色
            //所有角色
            List<Role> allrolelist=roleService.selectAll();
            Iterator<Role> it = allrolelist.iterator();
            while (it.hasNext()) {
                Role temp = it.next();
                for(Role e2:roleList){
                    if(temp.getId().compareTo(e2.getId())==0){
                        it.remove();
                    }
                }
            }
            List<Role> notinrolelist=allrolelist;
            resultmap.put("notinrolelist",notinrolelist);//用户不拥有的角色
            resultmap.put("status", "success");
            resultmap.put("message", "获取成功");
            return resultmap;
        } catch (Exception e) {
            e.printStackTrace();
            resultmap.put("status", "fail");
            resultmap.put("message", "获取失败，系统异常");
            return resultmap;
        }
    }

    //设置用户角色
    @ResponseBody
    @PostMapping(value = "/saveRoleSet")
    public ReturnMsg saveRoleSet(Integer[] role,Integer id) {
        try {
            // 根据用户id删除所有用户角色关联实体
            Example tuserroleexample=new Example(RoleUser.class);
            tuserroleexample.or().andEqualTo("userId",id);
            roleUserService.deleteByExample(tuserroleexample);

            if(role!=null && role.length>0){
                for(Integer roleid : role){
                    RoleUser roleUser=new RoleUser();
                    roleUser.setRoleId(roleid);
                    roleUser.setUserId(id);
                    roleUserService.saveNotNull(roleUser);
                }
            }
            return new ReturnMsg(true,"设置角色成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ReturnMsg(false,"系统异常");
        }
    }
}
